package com.cskaoyan.gateway.controller.user;

/**
 * @author pengyehua
 * @date 2020/12/19 18:22
 */

import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.IUserRegisterService;
import com.mall.user.annotation.Anonymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.KaptchaCodeRequest;
import com.mall.user.dto.KaptchaCodeResponse;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 用户注册
 */
@RestController
public class UserRegisterController {

    @Reference(check = false)
    IUserRegisterService userRegisterService;

    @Reference(check = false)
    IKaptchaService iKaptchaService;

    @PostMapping("user/register")
    @Anonymous
    public ResponseData userRegister(@RequestBody Map<String,String> map, HttpServletRequest request){
        //获取请求参数
        String userName =  map.get("userName");
        String userPwd =  map.get("userPwd");
        String captcha =  map.get("captcha");
        String email =  map.get("email");

        //判断验证码
        String kaptcha_uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        kaptchaCodeRequest.setCode(captcha);
        kaptchaCodeRequest.setUuid(kaptcha_uuid);
        KaptchaCodeResponse kaptchaCodeResponse = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        if(!kaptchaCodeResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getMsg());
        }
        //插入用户表和验证表，以及发送激活邮件
        UserRegisterRequest registerRequest = new UserRegisterRequest();
        registerRequest.setUserName(userName);
        registerRequest.setUserPwd(userPwd);
        registerRequest.setEmail(email);
        UserRegisterResponse response = userRegisterService.register(registerRequest);
        //出现异常，返回错误信息
        if(!response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        //正常返回数据
        return new ResponseUtil<>().setData(null);
    }
}
